<template>
  <div class="pie-chart">
		<div
			class="chart-box"
			ref="myRef"
		/>

  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, watch, defineProps, nextTick, computed, onMounted } from "vue";

const props = defineProps({
  legendStyle: {
    type: String,
    default: "",
  },
  color: {
    type: Array,
    default: () => {
      return [
				"#448FFF",
        "#F0696D",
        "#02BC76",
        "#EEB57F",
        "#448FFF",
        "#A97FEE",
        "#FFCD44",
      ];
    },
  },
  chartData: {
    type: Array,
    default: () => {
      return []
    }
  },
  isShowLegend:{
    type:Boolean,
    default:true
  },
  width: {
    type: Array,
    default: () => {
      return [33, 33, 33]
    }
  },
  unit: {
    type: String,
    default: ''
  },
  emphasis: {
    type: Object,
    default: () => ({})
  },
  // 环形图是否居中显示
  isCenter: {
    type: Boolean,
    default: false
  },
	position: {
		type: String,
		default: 'outer'
	}
})

const myRef = ref(null);
let myChart = null;

const initChart = () => {
  myChart = echarts.init(myRef.value);
  myChart.setOption({
    color: props.color,
    tooltip: {
      show: false,
      trigger: "item",
      borderWidth: 1,
      backgroundColor: "rgba(20, 38, 74, .9)",
      textStyle: {
				color: '#fff'
      },
    },
    series: [
      {
        type: "pie",
				silent: true,
				radius: props?.position === 'outer' ? ["0%", "55%"] : ["0%", "80%"],
        center: ["50%", "50%"],
        data: props.chartData,
				avoidLabelOverlap: false,
				labelLayout: {
					hideOverlap: false
				},
				label: {
					formatter: function(g) {
						let y = g.name.length >= 6 ? g.name.slice(0, 6) + `\n` + g.name.slice(6, g.name.length) : `` + g.name;
						return '{value|' + (g.value ?? 0) + props.unit + `}\n{v|` + y + '}'
					},
					alignTo: 'labelLine',
					position: props?.position,
					rich: {
						value: {
							color: props?.position === 'outer' ? '#FF505A' : '#FFCD44',
							fontSize: '14',
							lineHeight: 16,
							fontWeight: 'bold',
							fontFamily: 'DFPLiJinHeiW8',
							display: 'block'
						},
						v: {
							color: props?.position === 'outer' ? '#B9B9B9' : '#FFCD44',
							fontSize: '10',
							lineHeight: 12,
						}
					}
				},
			},
    ],
  })
}


watch(() => props.chartData, () => {
    nextTick(() => {
      if (myChart) myChart.dispose()
      initChart()
    })
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="less">
.pie-chart {
  width: 100%;
	.chart-box {
		width: 100%;
		height: 100%;
	}
}
</style>
